﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wicresoft.SMS.Data
{
    public class sqlCommonService : ICommonService
    {        
        IConnectStringProvider _csp;
        public sqlCommonService(IConnectStringProvider provider)
        {
            _csp = provider;
        }


        public IEnumerable<Department> GetDepartments()
        {
            using (var db = new Entities(_csp.ConnectionString)){
                return db.Department.ToList();
            }
        }

        public IEnumerable<Contact> GetContacts(string UserKey, string Password)
        {
            if(_csp == null)
                throw new NullReferenceException("IConnectStringProvider could not be null!");
            UserRoleService varifyUserService = new UserRoleService(_csp);
            if (!varifyUserService.ValidationUser(UserKey, Password))
                return null;
            User user;
            using (var db = new Entities(_csp.ConnectionString))
            {
                int keyid;
                if (int.TryParse(UserKey, out keyid)){
                    user = db.User.FirstOrDefault(p => (p.IsActive == true && (p.CIL == UserKey || p.Email == UserKey || p.UserID == keyid)));
                }
                else{
                    user = db.User.FirstOrDefault(p => (p.IsActive == true && (p.CIL == UserKey || p.Email == UserKey)));
                }
                if (user != null)
                {
                    user.Contact.Load();
                    foreach(var c in user.Contact)
                        c.Number.Load();
                }
            }
            if(user != null)
                return user.Contact;
            return null;
        }
    }
}
